<template>
    <div v-if="props.value" class="reference-box">
        <div class="reference-box-header">
            <div class="reference-title-box">
                <div class="reference-title">参考文献</div>
                <div class="operate-button close-button" @click="closeReference"></div>
            </div>
            <div class="header-operate-box">
                <a-tabs v-model:activeKey="activeKey">
                    <a-tab-pane key="1" tab="Tab 1"></a-tab-pane>
                    <a-tab-pane key="2" tab="Tab 2"></a-tab-pane>
                    <a-tab-pane key="3" tab="Tab 3"></a-tab-pane>
                    <template #rightExtra>
                        <div v-if="!props.currentPaper" class="operate-button filter-button"
                            @click="showFilter = !showFilter">
                        </div>
                    </template>
                </a-tabs>
            </div>
        </div>
        <div class="reference-box-content">
            <!-- {{ paperList }} -->
            <div v-for="(item, index) in paperList" v-show="total !== 0"
                :id="(limit * (current - 1) + index + 1).toString()" :key="item.paperId" :paper="item"
                class="reference-item" @click="openPagerDetail(item)">
                <div class="reference-item-title"> <span class="reference-item-index">{{ current <= 1 ? index + 1 :
                    ((current - 1) * 10) + index + 1}}</span>{{
                                item.title }}</div>
                <div v-if="item.titleCh && item.languageCode !== LANGUAGE_CODE.中文" class="reference-item-title">{{
                    item?.titleCh }}</div>
                <div class="reference-item-summary">{{ item?.researchContent || '暂无摘要' }}</div>
                <div v-if="item.researchContentCh && item.languageCode !== LANGUAGE_CODE.中文"
                    class="reference-item-summary-ch">
                    {{ item?.researchContentCh }}</div>
                <div class="reference-item-key">
                    {{ [item.modificationName]
                        .concat(item.mstMaterialPaperList.map((o) => o.materialNameEn))
                        .filter((o) => !!o)
                        .slice(0, 6).join(',') }}
                </div>
                <div class="reference-item-footer">
                    <div class="reference-item-footer-tag" :class="Object.keys(EDocumentType).find(key => EDocumentType[key as keyof typeof EDocumentType] === item.documentType)">{{DocumentTypeList.filter(i => i.code == item.documentType)[0].label }}</div>
                    <div v-if="hasPermission(item)" class="ic_go_prase_box" @click.stop="createdNewChat(item)">
                        <div class="ic_go_prase"></div>文档解读
                    </div>
                </div>
            </div>
        </div>
        <div v-if="total > 10" class="reference-box-footer">
            <a-pagination v-model:current="current" v-model:pageSize="limit" :total="total"
                :show-total="(total: number) => `共${total}条`" />
        </div>
        <PaperFilter v-model:visible="showFilter" :ids="ids" @filter="handleFilter" :initParam="initParam"
            @setInitParam="setInitParam" />
        <!-- <a-modal  v-model:visible="paperView"  style="top:128px;width: 800px;">
            <PaperItem v-if="currentPaper" :detail="true"  :paper="currentPaper" />
        </a-modal> -->

    </div>

</template>
<script setup lang="ts">
import { ref, watch, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { getMstPaperList, type IMstPaper } from '@/api/dialog'
import type { PdfFile } from '@/api/type';
import { DocumentTypeList, EDocumentType } from '@/api/type';
import { useUserInfoStore } from '@/stores/modules/userInfo';
import { LANGUAGE_CODE } from '@/const';
import { saveOrUpdate } from '@/api/dialog';
const showFilter = ref(false)
const loading = ref(false)
const query = ref({})
const total = ref(0)
const limit = ref(10)
const current = ref(1)
const props = defineProps<{
    value: boolean
    ids: string
    referenceIndex: string
    currentPaper: Object
}>()
const paperView = ref(false)
// const currentPaper = ref<IMstPaper>()
const router = useRouter()
const emit = defineEmits(['update:value', 'update:currentPaper', 'close-reference'])
const paperList = ref<Array<IMstPaper>>([])
const scrollIndex = ref<string>('')
const initParam = ref(null)
const setInitParam = (param: any) => {
    initParam.value = param
}
watch(() => props.ids, () => {
    if (!props.ids || !props.ids.length) return
    current.value = 1
    query.value = {}
    setInitParam(null)
    getPaperList()
}, { immediate: true })
watch(() => limit.value, getPaperList)
watch(() => current.value, getPaperList)
watch(() => props.referenceIndex, async () => {
    if (!props.referenceIndex) return
    scrollIndex.value = props.referenceIndex
    current.value = Math.ceil(Number(props.referenceIndex) / limit.value) || 1
    document?.getElementById(scrollIndex.value)?.scrollIntoView({
        behavior: "smooth", //smooth:平滑，auto：直接定位
        block: "start",
        inline: "start",
    });
    let newIndex = scrollIndex.value
    document?.getElementById(scrollIndex.value)?.classList.add('blinking-border')
    setTimeout(() => {
        document?.getElementById(newIndex)?.classList.remove('blinking-border')
    }, 3000)
})
watch(() => props.value, () => {
    console.log('props.value', props.value, props.referenceIndex)
    query.value = {}
    getPaperList()
})

// watch(() => props.index,()=>{
//     if(props.index < limit.value){
//         debounce(() => {
//     document?.getElementById(currentState.value.key + nv)?.scrollIntoView({
//       behavior: "smooth", //smooth:平滑，auto：直接定位
//       block: "start",
//       inline: "start",
//     });
//   }, 300)
//     }
// })
function handleFilter(q: any) {
    console.log('query', q)
    query.value = q
    current.value = 1
    loading.value = true
    getMstPaperList({
        ...query.value,
        ids: props.ids,
        limit: limit.value,
        current: current.value
    })
        .then((res) => {
            if (!res.data) return
            paperList.value = res.data.entity.rows
            total.value = res.data.entity.total
            showFilter.value = false

        })
        .finally(() => {
            loading.value = false
        })
}
const resetFilter = () => {
    if (!query.value || JSON.stringify(query.value) == "{}") return
    query.value = {}
    handleFilter(query.value)
}

defineExpose({ resetFilter })

function getPaperList() {
    if (!props.ids) return
    if (loading.value) return
    loading.value = true
    getMstPaperList({
        ...query.value,
        ids: props.ids,
        limit: limit.value,
        current: current.value
    })
        .then((res) => {
            if (!res.data) return
            const offset = limit.value * (current.value - 1)
            paperList.value = []
            paperList.value = res.data.entity.rows.map((o, index) => {
                return {
                    ...o,
                    index: offset + index + 1
                }
            })
            total.value = res.data.entity.total
            if (scrollIndex.value) {
                nextTick(() => {
                    let allDom = document.querySelectorAll('.blinking-border')
                    allDom.forEach((el) => {
                        el.classList.remove('blinking-border')
                    })
                    document?.getElementById(scrollIndex.value)?.scrollIntoView({
                        behavior: "smooth", //smooth:平滑，auto：直接定位
                        block: "start",
                        inline: "start",
                    });
                    let newIndex = scrollIndex.value
                    document?.getElementById(scrollIndex.value)?.classList.add('blinking-border')

                    setTimeout(() => {
                        document?.getElementById(newIndex)?.classList.remove('blinking-border')
                        scrollIndex.value = ''
                    }, 4000)

                })

            }
        })
        .finally(() => {
            //   scrollToTop()
            loading.value = false
        })
}
const openPagerDetail = (item: IMstPaper) => {
    // currentPaper.value = item
    paperView.value = true
    emit('update:currentPaper', item)
}
const goParse = (value: any) => {
    const pdfFile: PdfFile = {
        paperId: value.pdfId,
        url: value.pdfUrl,
        name: value.title,
        documentType: value.documentType,
    }
    router.push({
        path: `/chat/documentParsing/`,
        query: JSON.parse(JSON.stringify(pdfFile))
    })
}
const createdNewChat = (file) => {
    // console.log('file', file)
    const { pdfUrl, pdfId, title, documentType } = file
    if (!pdfUrl || !pdfId) return
    saveOrUpdate({
        id: '',
        userId: userInfo.id as string,
        dialogName: '',
        fileUrl: pdfUrl,
        pdfId: pdfId,
        fileSize: '',
        fileName: title,
        queryType: 2,
        processStatus: 3,
        documentType: documentType
    }).then((res) => {
        const pdfFile: PdfFile = {
            paperId: pdfId,
            url: pdfUrl,
            size: '',
            name: title,
            documentType
        }

        router.push({
            path: `/chat/documentParsing/${res.data.entity}`,
        })
    })
}
const userInfo = useUserInfoStore()
const hasPermission = (paper: IMstPaper) => {
    return paper.isPublicAccess === '1' || (paper.isPublicAccess === '0' && userInfo.authorityStatus === 1)
}

const closeReference = () => {
    emit('close-reference')
    emit('update:currentPaper', undefined)
    paperView.value = true
}
</script>
<style lang="scss" scoped>
@keyframes blink {
    0% {
        border-color: #2A8BF2;
    }

    50% {
        border-color: #E7F3FF;
    }

    100% {
        border-color: #2A8BF2;
    }
}

.blinking-border {
    animation: blink 1s 4;
}

.reference-box {
    width: 704px;
    margin-top: 24px;
    border-left: 1px solid #E7E9EC;
    height: calc(100% - 24px);
    display: flex;
    flex-direction: column;

    .reference-box-header {
        padding: 0 40px;

        .reference-title-box {
            display: flex;

            .reference-title {
                font-weight: 500;
                font-size: 20px;
                color: #0D1C2E;

            }

            .close-button {
                background-image: url('@/static/image/ic_close.png');
            }
        }


        .header-operate-box {

            .operate-button {
                width: 20px;
                height: 20px;
                background-repeat: no-repeat;
                background-position: center center;
                background-size: 20px 20px;
                cursor: pointer;
            }

            .filter-button {
                background-image: url('@/static/image/ic_filter.png');
                margin-right: 20px;
            }

        }
    }

    .reference-box-content {
        flex: 1;
        overflow-y: scroll;
        padding: 0 40px;

        .reference-item {
            cursor: pointer;
            margin-top: 20px;
            padding: 16px;
            background: linear-gradient(180deg, #E7F3FF 1%, #FFFFFF 43%, #FFFFFF 95%);
            border-radius: 4px;
            border: 2px solid #E7F3FF;

            .reference-item-title {
                color: #292929;
                font-size: 16px;
                font-weight: 600;
                line-height: 24px;
                margin-bottom: 18px;

                .reference-item-index {
                    width: 24px;
                    height: 24px;
                    border-radius: 50%;
                    color: #2A8BF2;
                    background: rgba(56, 117, 246, 0.1);
                    font-size: 14px;
                    display: inline-block;
                    text-align: center;
                    margin-right: 6px;
                }
            }

            .reference-item-summary-ch {
                color: #0D1C2E;
                overflow: hidden;
                white-space: normal;
                text-overflow: ellipsis;
                line-height: 23px;
                /* 弹性伸缩盒子模型显示 */
                display: -webkit-box;
                /* 显示的文本行数 */
                -webkit-line-clamp: 3;
                /* 子元素排列方式 */
                -webkit-box-orient: vertical;
                word-break: break-all;
                margin-bottom: 8px;
            }

            .reference-item-summary {
                color: #0D1C2E;
                overflow: hidden;
                white-space: normal;
                text-overflow: ellipsis;
                line-height: 23px;
                /* 弹性伸缩盒子模型显示 */
                display: -webkit-box;
                /* 显示的文本行数 */
                -webkit-line-clamp: 3;
                /* 子元素排列方式 */
                -webkit-box-orient: vertical;
                word-break: break-all;
                margin-bottom: 8px;
            }

            .reference-item-summary::before {
                content: '摘要：';
                font-weight: 600;
                color: #292929;
            }

            .reference-item-key {
                color: #0D1C2E;
                word-break: break-all;
            }

            .reference-item-key::before {
                content: '关键词：';
                color: #292929;
                font-weight: 600;
            }
        }

        .reference-item-footer {
            margin-top: 16px;
            display: flex;
            justify-content: space-between;
            color: #A3A4A5;
            .reference-item-footer-tag{
                padding: 4px 8px;
                border-radius: 4px;
                font-size: 12px;
                line-height: 12px;
            }
            .PATENT{
                border: 1px solid #E5F2DB;
                background: #F2FCEA;
            }
            .DOCUMENT{
                background: #F0F7FF;
                border: 1px solid #DDECFD;
            }
            .RECIPE{
                background: #FFF6F5;
                border: 1px solid #F8E3E3;
            }
            .WEB{
                background: #FFF6E8;
                border: 1px solid #F8EDDA;
            }
            .ic_go_prase_box {
                display: flex;
                color: #2183EA;
                cursor: pointer;

                .ic_go_prase {
                    background-image: url('@/static/image/ic_go_analysis.png');
                    width: 20px;
                    height: 20px;
                    background-repeat: no-repeat;
                    background-size: 20px;
                    margin-right: 6px;
                }
            }
        }
    }

    .reference-box-footer {
        height: 56px;
        border-top: 1px solid #E7E9EC;
        display: flex;
        align-items: center;
        flex-direction: row-reverse;
        padding: 0 20px;
    }
}
</style>